/**
 * 和行平台HTTP短信接口规范
 */
const httpResult = require("../lib/httpResult");
const _ = require("lodash");
let router = require('koa-router')();
const MyEmitter = require('../lib/MyEmitter');
const flashMsg = require('../lib/flashChannel').send;
const IPMsg = require('../lib/iPChannel').send;
const utils = require("../lib/utils");

const status = {
  MT : {
    Invalid_Parameter : '-100001',
    Verification_Fail : '-100001',
    INVALID_TS : '-1004',
    TS_TIMEOUT : '-1005',
    INVALID_TOKEN : '-1006',
    AUTH_FAIL : '-1007',
    INVALID_ORI_IP : '-1008',
    ACCOUNT_BALANCE_NOT_ENOUGH : '-100003',
    ACCOUNT_CLOSED : '-100004',
    ACCOUNT_NOT_IN_SERVICE_TIME : '-100004',
    MISS_DEST : '-100012',
    INVALID_DEST : '-100014',
    MISS_CONTENT : '-2501',
    CONTENT_OVER_LENGTH : '-2502',
    CONTENT_NOT_MATCH : '-2505',
    DEST_OVER_LENGTH : '-2303'
  }
}

let flashSender = new MyEmitter(10, flashMsg, async (result) => {console.log(result)});
flashSender.name = 'hxtx_sms_flash_send_thread';
flashSender.startup();

let IPSender = new MyEmitter(10, IPMsg, async (result) => {console.log(result)});
IPSender.name = 'hxtx_sms_ip_send_thread';
IPSender.startup();

router.get('/', async function (ctx, next) {
  ctx.state = {
    title: 'HXTX'
  };

  await ctx.render('index', {
  });
})

async function doSubmit(ctx, batch){
  // let admin = ctx.session.admin;
  log.info('submit info: ', ctx.request.body);

  let body = ctx.request.body;
  let reqLog = await models.mtRequestLog.create({body});

  // let customerInfo = await commonValid(ctx);

  let sms = body.sms;
  let result = [];

  for(let item of sms){
    console.log(item)
    let mt_record = {
      request_id : reqLog._id,
      account: body.appkey,
      mobile: item.phone,
      content: item.msg,
      charge_count : 0,
      ref: '',
      mt_msg_id : '',
      ext : item.extend
    }
    let record = await models.mtMsg.create(mt_record);
    //根据appkey分流：
    switch(body.appkey){
        case '80006': {
            //判断tplId
            record.tplId = 'faa95b737c22249aaea318c258eec352';
            flashSender.addTask(record);
            break;
        }
        case '089932' : {
          record.pwd = '696344';
          IPSender.addTask(record);
            break;
        }
    }

    result.push({
      status : '00000',
      phone: item.phone,
      desc : '提交成功',
      uid : record._id
    });
  }

  return {
    code : '00000',
    desc : '提交成功',
    result
  };
}

async function doSubmitBatch(ctx){
  return await doSubmit(ctx, true)
}

router.get('/submit', httpResult.respRaw(() => {
  throw({code : 405, message: 'METHOD NOT ALLOWED'});
}));

router.post('/send_single', httpResult.respRaw(doSubmit));
router.post('/send_batch', httpResult.respRaw(doSubmitBatch));

module.exports = router;
